package controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import object.PageBean;
import object.ZcAdmin;
import object.ZcOrderInfo;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import pojo.LogIncome;
import pojo.LogNoruserbill;
import pojo.ZcArea;
import pojo.ZcItem;
import pojo.ZcOrder;
import pojo.ZcOrderItem;
import pojo.ZcOrderLog;
import pojo.ZcUser;
import pojo.ZcUserAddr;
import service.Transaction2zcService;
import utils.CookieUtil;
import utils.GetHelper;
import utils.HttpRequestUtil;
import utils.JsonUtil;
import utils.MD5Helper;
import utils.OrderNumUtil;
import config.ConstantConfig;
import config.SysConfig;

/**
 * 
 * @author hdq
 *
 */
@Controller
@RequestMapping("transaction2zc")
public class Transaction2zcController {

	@Autowired
	private Transaction2zcService transaction2zcService;
	
	private static Logger logger = Logger.getLogger(Transaction2zcController.class);
	
	
	/**
	 * 0000接口
	 * 进入早餐应用
	 * @param code
	 * @param req
	 * @return
	 */
	@RequestMapping("intoZc")
	//@ResponseBody
	public String intoZc(
			@RequestParam("code") String code,
			HttpServletRequest httpRequest,RedirectAttributes attr) {
		String openid="";
		try {
//			String url = SysConfig.get_openId_url+code;
//			JSONObject result = HttpRequestUtil.httpRequestRjson(url, "GET", null);
//			//没找到会报错Exception in thread "main" net.sf.json.JSONException: JSONObject["errcode1"] not found.
//			openid=result.getString("openid");
			openid="oNtWKjr4azG8R5A7J2gRI4OawFyQ";
			ZcUser user=transaction2zcService.queryZcUser(openid);
			if(user!=null){
				httpRequest.getSession().setAttribute("user", user);
				httpRequest.getSession().setAttribute("zcwx", 1);
			}else{
				ZcUser e=new ZcUser(null, openid);
				if(transaction2zcService.saveZcUser(e)){
					httpRequest.getSession().setAttribute("user", e);
					httpRequest.getSession().setAttribute("zcwx", 1);
				}else{
					attr.addAttribute("errorMsg", "服务器繁忙");
					return "redirect:/web2zc/returnMsg.jsp";
				}
			}
			return "redirect:/index2zc.jsp";
		} catch (Exception e) {
			e.printStackTrace();
			attr.addAttribute("errorMsg", "服务器繁忙");
			return "redirect:/web2zc/returnMsg.jsp";
		}
	}
	
	/**
	 * 0001接口
	 * 早餐配送区域查询
	 * @param curPage
	 * @param pageSize
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("landmarkQuery")
	@ResponseBody
	public HashMap<String, Object> landmarkQuery(
			@RequestParam(value = "city", defaultValue = "福州市") String city,
			@RequestParam(value = "curPage", defaultValue = "1") Integer curPage,
			@RequestParam(value = "pageSize", defaultValue = "4") Integer pageSize,
			HttpServletRequest req) {
		HashMap<String, Object> response = new HashMap<>();
		PageBean<ZcArea> page=null;
		try {
			page = transaction2zcService.queryLandmark(city,curPage, pageSize);
			response.put("responseCode", "00000");
			response.put("response", ConstantConfig.QUERY_SUCCESS);
			response.put("page", page);
		} catch (Exception e) {
			e.printStackTrace();
			response.put("responseCode", "E0001");
			response.put("response", ConstantConfig.EXCEPTION_OCCURS);
			e.printStackTrace();
		}
		return response;
	}
	
	/**
	 * 0002接口
	 * 交易订单查询
	 * @param orderNum
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("zcOrderQuery")
	@ResponseBody
	public HashMap<String, Object> zcOrderQuery(
			HttpServletRequest httpRequest) {
		HttpSession session=httpRequest.getSession();
		ZcUser user=(ZcUser) session.getAttribute("user");
		HashMap<String, Object> response = new HashMap<>();
		List<ZcOrder> list = null;
		try {
			list = transaction2zcService.queryZcOrder(user.getId(),"0");//0表示订单服务中
			response.put("responseCode", "00000");
			response.put("response", ConstantConfig.QUERY_SUCCESS);
			response.put("list", list);
		} catch (Exception e) {
			e.printStackTrace();
			response.put("responseCode", "E0001");
			response.put("response", ConstantConfig.EXCEPTION_OCCURS);
			e.printStackTrace();
		}
		return response;
	}
	
	/**
	 * 0003接口
	 * 已完成订单查询
	 * @param curPage
	 * @param pageSize
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("zcOrderCompletedQuery")
	@ResponseBody
	public HashMap<String, Object> zcOrderCompletedQuery(
			@RequestParam(value = "curPage", defaultValue = "1") Integer curPage,
			@RequestParam(value = "pageSize", defaultValue = "3") Integer pageSize,
			HttpServletRequest req) {
		HttpSession session=req.getSession();
		ZcUser user=(ZcUser) session.getAttribute("user");
		HashMap<String, Object> response = new HashMap<>();
		PageBean<ZcOrder> page=null;
		try {
			page = transaction2zcService.queryZcOrderCompleted(user.getId(),curPage, pageSize);
			response.put("responseCode", "00000");
			response.put("response", ConstantConfig.QUERY_SUCCESS);
			response.put("page", page);
		} catch (Exception e) {
			e.printStackTrace();
			response.put("responseCode", "E0001");
			response.put("response", ConstantConfig.EXCEPTION_OCCURS);
			e.printStackTrace();
		}
		return response;
	}
	
	/**
	 * 0011接口
	 * 加载早餐列表
	 * @param curPage
	 * @param pageSize
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("zcItemsQuery")
//	@ResponseBody
	public String zcItemsQuery(
			@RequestParam(value = "landmarkId", defaultValue = "1") Integer landmarkId,
			@RequestParam(value = "sendWeek",defaultValue="0") int sendWeek,//本周
			HttpServletRequest req,RedirectAttributes attr) {
		List<ZcItem> list = null;
		int nowWeek=0;
		try {
			//int i=1/0;
			list = transaction2zcService.queryZcItems(landmarkId);
			SimpleDateFormat df = new SimpleDateFormat("MM/dd");
			Calendar cal = Calendar.getInstance();
			int w=cal.get(Calendar.DAY_OF_WEEK);
			int itemSize=0;
			double total=0;
			if(w<1||w>5){
				//下个星期一
				cal.add(Calendar.DATE, 9-w);
				w=1;
				nowWeek=1;
				sendWeek=1;
			}
			if(sendWeek==1&&nowWeek==0){//切换下个星期
				cal.add(Calendar.DATE, 9-w);
				w=1;
			}
			for (ZcItem zcItem : list) {
				Integer zcweek=Integer.valueOf(zcItem.getWeek())+1;
				if(zcweek>w){
					zcItem.setSell(true);
					itemSize++;
					total+=zcItem.getPrice();
				}
				cal.set(Calendar.DAY_OF_WEEK, zcweek);
				zcItem.setSellTime(df.format(cal.getTime()));
			}
//			ZcArea areaInfo=new ZcArea();
//			req.getSession().setAttribute("areaInfo", areaInfo);
			//优化一下只放回json数据
			req.setAttribute("responseCode", "00000");
			req.setAttribute("response", ConstantConfig.QUERY_SUCCESS);
			req.setAttribute("list", list);
			req.setAttribute("listJson", JsonUtil.beanListToJson(list));
			req.setAttribute("itemSize", itemSize);
			req.setAttribute("total", total);
			req.setAttribute("sendWeek", sendWeek);
			req.setAttribute("nowWeek", nowWeek);
		} catch (Exception e) {
			e.printStackTrace();
			attr.addAttribute("errorMsg", "服务器繁忙");
			return "redirect:/web2zc/returnMsg.jsp";
		}
		return "forward:/web2zc/item/item.jsp?landmarkId="+landmarkId;
	}
	
	/**
	 * 0012接口
	 * 用户下单详情
	 * @param curPage
	 * @param pageSize
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("zcOrderPlace")
//	@ResponseBody
	public String zcOrderPlace(
			@RequestParam(value = "orderJson") String orderJson,
			HttpServletRequest req,RedirectAttributes attr) {
		HttpSession session=req.getSession();
		ZcUser user=(ZcUser) session.getAttribute("user");
		session.setAttribute("orderJson", orderJson);
		try {
			//json数据转成对象
			String[] excludes={"userName","userMp","aId","remark"};
			JsonConfig config = new JsonConfig();    
	        config.setIgnoreDefaultExcludes(false);       
	        config.setExcludes(excludes);//只要设置这个数组，指定过滤哪些字段。 
			JSONObject jsonObject = JSONObject.fromObject(orderJson,config);
			Map<String, Class> classMap = new HashMap<String, Class>();  
	        classMap.put("list", ZcItem.class);  
	        ZcOrderInfo o=(ZcOrderInfo) jsonObject.toBean(jsonObject, ZcOrderInfo.class,classMap);
//			ZcOrderInfo o=JsonUtil.jsonToBean(orderJson, ZcOrderInfo.class);
	        ZcUserAddr addr=transaction2zcService.queryZcUserAddr(user.getId(), o.getUserAreaId());
			req.setAttribute("responseCode", "00000");
			req.setAttribute("response", ConstantConfig.QUERY_SUCCESS);
			req.setAttribute("zcOrder", o);
			if(addr==null){
				ZcArea area=transaction2zcService.queryZcArea(o.getUserAreaId());
				addr=new ZcUserAddr();
				addr.setArea(area.getArea());
				addr.setAreaId(area.getId());
			}
			req.setAttribute("zcAddr", addr);
		} catch (Exception e) {
			e.printStackTrace();
			attr.addAttribute("errorMsg", "服务器繁忙");
			return "redirect:/web2zc/returnMsg.jsp";
		}
		return "forward:/web2zc/order/order.jsp";
	}
	
	/**
	 * 0013接口
	 * 提交订单
	 * orderJson  订单的json数据
	 * @return
	 */
	@RequestMapping("zcOrderCommit")
	@ResponseBody
	public HashMap<String, Object> zcOrderCommit(
			@RequestParam(value = "orderJson") String orderJson,
			HttpServletRequest httpRequest) {
		HashMap<String, Object> response = new HashMap<>();
		//要为session加过滤器判断是否获得
		HttpSession session=httpRequest.getSession();
		ZcUser user=(ZcUser) session.getAttribute("user");
		try {
			JSONObject jsonObject = JSONObject.fromObject(orderJson);
			Map<String, Class> classMap = new HashMap<String, Class>();  
	        classMap.put("list", ZcItem.class);  
	        ZcOrderInfo o=(ZcOrderInfo) jsonObject.toBean(jsonObject, ZcOrderInfo.class,classMap);
	        ZcUserAddr addr=transaction2zcService.queryZcUserAddr(user.getId(), o.getUserAreaId());
	        if(addr==null){
	        	if(o.getAid()!=null&&!"".equals(o.getAid())){//地址id不为空
	        		transaction2zcService.editZcUserAddrToDef(o.getAid());
	 	        }else{
	 	        	addr=new ZcUserAddr(null, user.getId(), o.getUserAreaId(), o.getUserName(), o.getUserMp(), o.getUserArea(), o.getUserAddress(), "1");
		        	transaction2zcService.saveZcUserAddr(addr);
	 	        }
	        }
	        o.setUserId(user.getId());
	        String orderNum=transaction2zcService.saveOrder(o);
	        response.put("responseCode", "00000");
	        response.put("orderNum", orderNum);
	        response.put("total", o.getTotal());
			response.put("response", ConstantConfig.QUERY_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			response.put("responseCode", "E0001");
			response.put("response", ConstantConfig.EXCEPTION_OCCURS);
			e.printStackTrace();
		}
		return response;
	}
	

	
	/**
	 * 0021接口
	 * 订单日志
	 * @param curPage
	 * @param pageSize
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("zcOrderLog")
	@ResponseBody
	public HashMap<String, Object> zcOrderLog(
			@RequestParam(value = "orderNum") String orderNum,
			HttpServletRequest req) {
		List<ZcOrderLog> list = null;
		HashMap<String, Object> response = new HashMap<>();
		try {
			list = transaction2zcService.queryZcOrderLog(orderNum);
			response.put("responseCode", "00000");
			response.put("response", ConstantConfig.QUERY_SUCCESS);
			response.put("list", list);
		} catch (Exception e) {
			e.printStackTrace();
			response.put("responseCode", "E0001");
			response.put("response", ConstantConfig.EXCEPTION_OCCURS);
		}
		return response;
	}
	
	/**
	 * 0022接口
	 * 订单详情
	 * @param curPage
	 * @param pageSize
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("zcOrderDetail")
	public String zcOrderDetail(
			@RequestParam(value = "curPage") String curPage,
			@RequestParam(value = "orderNum") String orderNum,
			HttpServletRequest req,RedirectAttributes attr) {
		List<ZcOrderItem> list = null;
		try {
			list = transaction2zcService.queryZcOrderItems(orderNum);
			SimpleDateFormat df = new SimpleDateFormat("MM/dd");
			Calendar cal = Calendar.getInstance();
			for (ZcOrderItem e : list) {
				cal.setTime(e.getSendTime());
				int gweek=cal.get(Calendar.DAY_OF_WEEK)-1;
				String gsellTime=df.format(e.getSendTime());
				e.setGweek(gweek+"");
				e.setGsellTime(gsellTime);
			}
			req.setAttribute("list", list);
		} catch (Exception e) {
			e.printStackTrace();
			attr.addAttribute("errorMsg", "服务器繁忙");
			return "redirect:/web2zc/returnMsg.jsp";
		}
		return "forward:/web2zc/order/orderItems.jsp?curPage="+curPage;
	}
	
	/**
	 * 0031接口
	 * 地址查询
	 * @return
	 */
	@RequestMapping("zcAddressQuery")
	public String zcAddressQuery(
			@RequestParam(value = "areaId") Integer areaId,
			HttpServletRequest httpRequest,RedirectAttributes attr) {
		//要为session加过滤器判断是否获得
		HttpSession session=httpRequest.getSession();
		ZcUser user=(ZcUser) session.getAttribute("user");
		List<ZcUserAddr> list = null;
		try {
			list = transaction2zcService.queryZcUserAddrsList(user.getId(),areaId);//0表示订单服务中
			httpRequest.setAttribute("list", list);
			httpRequest.setAttribute("areaId", areaId);
			if(list.size()>0){
				httpRequest.setAttribute("area", list.get(0).getArea());
			}else{
				ZcArea zcArea=transaction2zcService.queryZcArea(areaId);
				httpRequest.setAttribute("area", zcArea.getArea());
			}
		} catch (Exception e) {
			e.printStackTrace();
			attr.addAttribute("errorMsg", "服务器繁忙");
			return "redirect:/web2zc/returnMsg.jsp";
		}
		return "forward:/web2zc/person/addrManage.jsp";
	}
	
	/**
	 * 0032接口
	 * 地址添加
	 * @return
	 */
	@RequestMapping("zcAddressNew")
	public String zcAddressNew(
			@ModelAttribute ZcUserAddr zcUserAddr,
			HttpServletRequest httpRequest,RedirectAttributes attr) {
		//要为session加过滤器判断是否获得
		HttpSession session=httpRequest.getSession();
		ZcUser user=(ZcUser) session.getAttribute("user");
		try {
			zcUserAddr.setUserId(user.getId());
			if(transaction2zcService.usaveZcUserAddr(zcUserAddr)){
				attr.addAttribute("areaId", zcUserAddr.getAreaId());
				attr.addAttribute("funcID", "0031");
				return "redirect:transaction2zcRouter";
			}else{
				attr.addAttribute("errorMsg", "服务器繁忙");
				return "redirect:/web2zc/returnMsg.jsp";
			}
		} catch (Exception e) {
			e.printStackTrace();
			attr.addAttribute("errorMsg", "服务器繁忙");
			return "redirect:/web2zc/returnMsg.jsp";
		}
	}
	
	/**
	 * 0033接口
	 * 地址修改UI
	 * @return
	 */
	@RequestMapping("zcAddressEditUI")
	public String zcAddressEditUI(
			@RequestParam(value = "id") Integer id,
			HttpServletRequest httpRequest,RedirectAttributes attr) {
		try {
			ZcUserAddr addr = transaction2zcService.queryZcUserAddrsById(id);
			httpRequest.setAttribute("addr", addr);
		} catch (Exception e) {
			e.printStackTrace();
			attr.addAttribute("errorMsg", "服务器繁忙");
			return "redirect:/web2zc/returnMsg.jsp";
		}
		return "forward:/web2zc/person/addrEdit.jsp";
	}
	
	/**
	 * 0034接口
	 * 地址修改
	 * @return
	 */
	@RequestMapping("zcAddressEdit")
	public String zcAddressEdit(
			@ModelAttribute ZcUserAddr zcUserAddr,
			HttpServletRequest httpRequest,RedirectAttributes attr) {
		//要为session加过滤器判断是否获得
		try {
			if(transaction2zcService.ueditZcUserAddr(zcUserAddr)){
				attr.addAttribute("areaId", zcUserAddr.getAreaId());
				attr.addAttribute("funcID", "0031");
				return "redirect:transaction2zcRouter";
			}else{
				attr.addAttribute("errorMsg", "服务器繁忙");
				return "redirect:/web2zc/returnMsg.jsp";
			}
		} catch (Exception e) {
			e.printStackTrace();
			attr.addAttribute("errorMsg", "服务器繁忙");
			return "redirect:/web2zc/returnMsg.jsp";
		}
	}
	
	/**
	 * 0035接口
	 * 地址删除
	 * @return
	 */
	@RequestMapping("zcAddressDel")
	public String zcAddressDel(
			@RequestParam(value = "id") Integer id,
			@RequestParam(value = "areaId") Integer areaId,
			HttpServletRequest httpRequest,RedirectAttributes attr) {
		//要为session加过滤器判断是否获得
		try {
			if(transaction2zcService.delZcUserAddr(id)){
				attr.addAttribute("areaId", areaId);
				attr.addAttribute("funcID", "0031");
				return "redirect:transaction2zcRouter";
			}else{
				attr.addAttribute("errorMsg", "服务器繁忙");
				return "redirect:/web2zc/returnMsg.jsp";
			}
		} catch (Exception e) {
			e.printStackTrace();
			attr.addAttribute("errorMsg", "服务器繁忙");
			return "redirect:/web2zc/returnMsg.jsp";
		}
	}
	
	
	/**
	 * 0036接口
	 * 地址切换
	 * @return
	 */
	@RequestMapping("zcAddressCut")
	public String zcAddressCut(
			@RequestParam(value = "id") Integer id,
			HttpServletRequest httpRequest,RedirectAttributes attr) {
		//要为session加过滤器判断是否获得
		HttpSession session=httpRequest.getSession();
		try {
			String orderJson=(String) session.getAttribute("orderJson");
			if(orderJson!=null&&!"".equals(orderJson)){
				String[] excludes={"userName","userMp"};
				JsonConfig config = new JsonConfig();    
		        config.setIgnoreDefaultExcludes(false);       
		        config.setExcludes(excludes);//只要设置这个数组，指定过滤哪些字段。 
				JSONObject jsonObject = JSONObject.fromObject(orderJson,config);
				Map<String, Class> classMap = new HashMap<String, Class>();  
		        classMap.put("list", ZcItem.class);  
		        ZcOrderInfo o=(ZcOrderInfo) jsonObject.toBean(jsonObject, ZcOrderInfo.class,classMap);
		        ZcUserAddr addr=transaction2zcService.queryZcUserAddrsById(id);
		        httpRequest.setAttribute("responseCode", "00000");
		        httpRequest.setAttribute("response", ConstantConfig.QUERY_SUCCESS);
		        httpRequest.setAttribute("zcOrder", o);
		        httpRequest.setAttribute("zcAddr", addr);
			}else{
				attr.addAttribute("errorMsg", "订单失效");
				return "redirect:/web2zc/returnMsg.jsp";
			}
		} catch (Exception e) {
			e.printStackTrace();
			attr.addAttribute("errorMsg", "服务器繁忙");
			return "redirect:/web2zc/returnMsg.jsp";
		}
		return "forward:/web2zc/order/order.jsp";
	}
	
	
	/**
	 * 0041接口
	 * 快递员登录
	 * @return
	 */
	@RequestMapping("adminLogin")
	public String adminLogin(
			@RequestParam(value = "loginName") String loginName,
			@RequestParam(value = "loginPsd") String loginPsd,
			@RequestParam(value = "rememberme",defaultValue="0") String rememberme,
			HttpServletRequest httpRequest,HttpServletResponse response,RedirectAttributes attr) {
		//要为session加过滤器判断是否获得
		HttpSession session=httpRequest.getSession();
		try {
			ZcAdmin admin=transaction2zcService.getZcAdmin(loginName);
			if(admin!=null){
				if(admin.getWebPwd().equalsIgnoreCase(MD5Helper.getMD5Str(loginPsd))){
					session.setAttribute("admin", admin);
					session.setAttribute("zcwx", 1);
					if("1".equals(rememberme)){
						CookieUtil.saveCookie(admin, response); 
					}
				}else{
					httpRequest.setAttribute("errorMsg", "密码错误");
					return "forward:/web2zc/login.jsp";
				}
			}else{
				httpRequest.setAttribute("errorMsg", "没获取到该用户");
				return "forward:/web2zc/login.jsp";
			}
		} catch (Exception e) {
			e.printStackTrace();
			httpRequest.setAttribute("errorMsg", "服务器繁忙");
			return "forward:/web2zc/login.jsp";
		}
		return "redirect:/web2zc/admin/sendOrder.jsp";
	}
	
	/**
	 * 0042接口
	 * 快递员配送订单接口
	 * @param curPage
	 * @param pageSize
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("zcSendItemQuery")
	@ResponseBody
	public HashMap<String, Object> zcSendItemQuery(
			@RequestParam(value = "curPage", defaultValue = "1") Integer curPage,
			@RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
			@RequestParam(value = "sendData", defaultValue = "0") String sendData,
			HttpServletRequest req) {
		HttpSession session=req.getSession();
		ZcAdmin admin=(ZcAdmin) session.getAttribute("admin");
		HashMap<String, Object> response = new HashMap<>();
		PageBean<ZcOrderItem> page=null;
		//Integer userId=10018;
		Integer userId=admin.getUserId();
		try {
			Calendar cl=Calendar.getInstance();
			int year=cl.get(Calendar.YEAR);
			int month=cl.get(Calendar.MONTH)+1;
			int date=cl.get(Calendar.DATE);
			SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy/MM/dd HH:mm:ss" );
			SimpleDateFormat df =   new SimpleDateFormat( "yyyy/MM/dd" );
			Date sdate = sdf.parse( year+"/"+month+"/"+date+" 08:30:00" );
			Date sdate1 = sdf.parse( year+"/"+month+"/"+date+" 10:00:00" );
			if("1".equals(sendData)){
				sdate = sdf.parse( year+"/"+month+"/"+(date+1)+" 08:30:00" );
				sdate1 = sdf.parse( year+"/"+month+"/"+date+" 10:00:00" );
			}
			Timestamp sendTime=new Timestamp(sdate.getTime());
			Timestamp sendTime1=new Timestamp(sdate1.getTime());
			String now=df.format(sdate);
			page = transaction2zcService.querySendItems(userId,sendTime,sendTime1,curPage, pageSize);
			response.put("responseCode", "00000");
			response.put("response", ConstantConfig.QUERY_SUCCESS);
			response.put("page", page);
			response.put("now", now);
		} catch (Exception e) {
			e.printStackTrace();
			response.put("responseCode", "E0001");
			response.put("response", ConstantConfig.EXCEPTION_OCCURS);
			e.printStackTrace();
		}
		return response;
	}
	
	
	/**
	 * 0043接口
	 * 按手机查询今天的订单
	 * @param curPage
	 * @param pageSize
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("zcSendItemQueryByMp")
	@ResponseBody
	public HashMap<String, Object> zcSendItemQueryByMp(
			@RequestParam(value = "userMp") String userMp,
			HttpServletRequest req) {
		HttpSession session=req.getSession();
		ZcAdmin admin=(ZcAdmin) session.getAttribute("admin");
		HashMap<String, Object> response = new HashMap<>();
		List<ZcOrderItem> list=null;
		//Integer userId=10018;
		Integer userId=admin.getUserId();
		try {
			Calendar cl=Calendar.getInstance();
			int year=cl.get(Calendar.YEAR);
			int month=cl.get(Calendar.MONTH)+1;
			int date=cl.get(Calendar.DATE);
			SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy/MM/dd HH:mm:ss" );
			SimpleDateFormat df =   new SimpleDateFormat( "yyyy/MM/dd" );
			Date sdate = sdf.parse( year+"/"+month+"/"+date+" 08:30:00" );
			Timestamp sendTime=new Timestamp(sdate.getTime());
			list = transaction2zcService.querySendItemsByMp(userId,sendTime,userMp);
			String now=df.format(sdate);
			response.put("responseCode", "00000");
			response.put("response", ConstantConfig.QUERY_SUCCESS);
			response.put("list", list);
			response.put("now", now);
		} catch (Exception e) {
			e.printStackTrace();
			response.put("responseCode", "E0001");
			response.put("response", ConstantConfig.EXCEPTION_OCCURS);
			e.printStackTrace();
		}
		return response;
	}
	
	
	/**
	 * 0044接口
	 * 结束订单
	 * @param curPage
	 * @param pageSize
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("zcSendItemEnd")
	@ResponseBody
	public HashMap<String, Object> zcSendItemEnd(
			@RequestParam(value = "id") Integer id,
			HttpServletRequest req) {
		HttpSession session=req.getSession();
		ZcAdmin admin=(ZcAdmin) session.getAttribute("admin");
		HashMap<String, Object> response = new HashMap<>();
//		Integer userId=10018;
//		String userMp="18506822511";
		Integer userId=admin.getUserId();
		String userMp=admin.getMobileNum();
		try {
			String result = transaction2zcService.endSendItem(id,userId,userMp);
			response.put("responseCode", "00000");
			response.put("response",result);
		} catch (Exception e) {
			e.printStackTrace();
			response.put("responseCode", "E0001");
			response.put("response", ConstantConfig.EXCEPTION_OCCURS);
			e.printStackTrace();
		}
		return response;
	}
	
	

	
	


	
//======================================微信相关方法===========================================	
	
	/**
	 * 0013/0017接口
	 * 微信支付的方法调用
	 * @param out_trade_no
	 * @param total_fee
	 * @param body
	 * @param openid
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("wxPayApi")
	@ResponseBody
	public String wxPayApi(
			@RequestParam("out_trade_no") String out_trade_no,
			@RequestParam("total_fee") double total_fee,
			@RequestParam("body") String body,
			@RequestParam("userMp") String userMp,
			@RequestParam("curPage") String curPage,
			HttpServletRequest httpRequest) {
		String result = null;
		HttpSession session=httpRequest.getSession();
		ZcUser user=(ZcUser) session.getAttribute("user");
		try {
			//封装统一下单接口参数
			total_fee=1;
			int total=(int)total_fee;
			String openid=user.getWxid();
			String nonceStr=OrderNumUtil.getNonceStr("JRZC");
			String urlBody = "appid="+SysConfig.appid+"&body="+body+"&mch_id="+SysConfig.mch_id+
					"&nonce_str="+nonceStr+"&notify_url="+SysConfig.notify_url_zc+"&openid="+openid+
					"&out_trade_no="+out_trade_no+"&spbill_create_ip="+SysConfig.spbill_create_ip+
					"&total_fee="+total+"&trade_type="+SysConfig.trade_type;
			String md5String = urlBody+"&key="+SysConfig.wx_pay_key;
			String sign = MD5Helper.getEncoderByMd5(md5String).toUpperCase();
			String url = "<xml>"
							+ "<appid>"+SysConfig.appid+"</appid>"
							+ "<body>"+body+"</body>"
							+ "<mch_id>"+SysConfig.mch_id+"</mch_id>"
							+ "<nonce_str>"+nonceStr +"</nonce_str>"
							+ "<notify_url>"+SysConfig.notify_url_zc+"</notify_url>"
							+ "<openid>"+openid+"</openid>"
							+ "<out_trade_no>"+out_trade_no+"</out_trade_no>"
							+ "<spbill_create_ip>"+SysConfig.spbill_create_ip+"</spbill_create_ip>"
							+ "<total_fee>"+total+"</total_fee>"
							+ "<trade_type>"+SysConfig.trade_type+"</trade_type>"
							+ "<sign>"+sign+"</sign>"
						+ "</xml>";
			//解析返回的统一下单接口结果
			result = HttpRequestUtil.httpRequest(SysConfig.unifiedorder_url, "POST", url);
			Document doc = DocumentHelper.parseText(result);
			String returnCode = doc.selectSingleNode("/xml/return_code").getText();
			
			//根据放回结果封装jsapi接口参数
			if("SUCCESS".equals(returnCode)){
				String resultCode = doc.selectSingleNode("/xml/result_code").getText();
				if("SUCCESS".equals(resultCode)){
					String appId = doc.selectSingleNode("/xml/appid").getText();
					String prepayId = "prepay_id="+doc.selectSingleNode("/xml/prepay_id").getText();
					Date now=new Date();
					String timeStamp = (now.getTime()+"").substring(0, 10);
					String resultBody = "appId="+SysConfig.appid+"&nonceStr="+nonceStr+"&package="+prepayId+"&signType=MD5&timeStamp="+timeStamp;
					String resultmd5String = resultBody+"&key="+SysConfig.wx_pay_key;
					String paySign = MD5Helper.getEncoderByMd5(resultmd5String).toUpperCase();
					result = "<xml>"
								+ "<return_code>"+returnCode+"</return_code>"
								+ "<result_code>"+resultCode+"</result_code>"
								+ "<out_trade_no>"+out_trade_no+"</out_trade_no>"
								+ "<curPage>"+curPage+"</curPage>"
								+ "<appId>"+appId+"</appId>"
								+ "<timeStamp>"+timeStamp +"</timeStamp>"
								+ "<nonce_str>"+nonceStr+"</nonce_str>"
								+ "<package>"+prepayId+"</package>"
								+ "<signType>"+SysConfig.sign_type+"</signType>"
								+ "<paySign>"+paySign+"</paySign>"
							+ "</xml>";
					//记录支付、充值记录
					transaction2zcService.insertLogBill(openid,userMp ,out_trade_no, new BigDecimal(total_fee));
				}
			}
		} catch (Exception e) {
			result="<xml>"+
					   "<return_code><![CDATA[ERROR]]></return_code>"+
					   "<return_msg><![CDATA[服务器繁忙]]></return_msg>"+
					"</xml>";
		}
		return result;
	}
	
	/**
	 * 0018接口
	 * 微信订单查询方法调用
	 * @param out_trade_no
	 * @param total_fee
	 * @param body
	 * @param openid
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("wxPayStatus")
	public String wxPayStatus(
			@RequestParam("curPage") String curPage,
			@RequestParam("out_trade_no") String out_trade_no,
			HttpServletRequest req) {
		String result = null;
		try {
			ZcOrder o = transaction2zcService.queryZcOrderByNum(out_trade_no);
			
			//判断是否支付
			if(o!=null&&ConstantConfig.TRANSACTION_NOTPAY.equals(o.getPayStatus())){
				//封装订单查询接口参数
				String nonceStr=OrderNumUtil.getNonceStr();
				String urlBody = "appid="+SysConfig.appid+"&mch_id="+SysConfig.mch_id+"&nonce_str="+nonceStr+"&out_trade_no="+out_trade_no;//+"&out_trade_no="+out_trade_no;
				String md5String = urlBody+"&key="+SysConfig.wx_pay_key;
				String sign = MD5Helper.getEncoderByMd5(md5String).toUpperCase();
				String url = "<xml>"
								+ "<appid>"+SysConfig.appid+"</appid>"
								+ "<mch_id>"+SysConfig.mch_id+"</mch_id>"
								+ "<nonce_str>"+nonceStr +"</nonce_str>"
								+ "<out_trade_no>"+out_trade_no+"</out_trade_no>"
								+ "<sign>"+sign+"</sign>"
							+ "</xml>";
				result = GetHelper.doHttpPost(SysConfig.orderQuery_url, url);
				//解析返回的订单查询接口结果
				Document doc = DocumentHelper.parseText(result);
				String returnCode = doc.selectSingleNode("/xml/return_code").getText();//result_code
				if("SUCCESS".equals(returnCode)){
					String resultCode = doc.selectSingleNode("/xml/result_code").getText();
					if("SUCCESS".equals(resultCode)){
						String tradeState = doc.selectSingleNode("/xml/trade_state").getText();
						if("SUCCESS".equals(tradeState)){
							String total_fee = doc.selectSingleNode("/xml/total_fee").getText();
							String openId = doc.selectSingleNode("/xml/openid").getText();
							String transaction_id=doc.selectSingleNode("/xml/transaction_id").getText();
							//判断是充值还是支付
							transaction2zcService.editZcOrderStatus(openId, out_trade_no, transaction_id, new BigDecimal(total_fee));
						}
					}
				}
			}
		} catch (Exception e) {
			req.setAttribute("resultCode", "E0001");
			req.setAttribute("returnlMsg", "服务器繁忙");
			return "forward:/index2zc.jsp?toPage=1&curPage="+curPage;
		}
		
		return "forward:/index2zc.jsp?toPage=1&curPage="+curPage;
		
	}
	
	/**
	 * 微信支付通知
	 * @param httpRequest
	 * @param httpResponse
	 * @throws DocumentException 
	 */
	@RequestMapping("wxPayed")
	@ResponseBody
	public void wxPayed(HttpServletRequest httpRequest,HttpServletResponse httpResponse) throws Exception {
		InputStream inStream;
		try {
			inStream = httpRequest.getInputStream();
			ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = inStream.read(buffer)) != -1) {
		    	outSteam.write(buffer, 0, len);
			}
			outSteam.close();
			inStream.close();
			String result  = new String(outSteam.toByteArray(),"utf-8");//获取微信调用我们notify_url的返回信息
			Document doc = DocumentHelper.parseText(result);
			String returnCode = doc.selectSingleNode("/xml/return_code").getText();
			if("SUCCESS".equalsIgnoreCase(returnCode)){
				String outTradeNo = doc.selectSingleNode("/xml/out_trade_no").getText();
				String total_fee = doc.selectSingleNode("/xml/total_fee").getText();
				String openId = doc.selectSingleNode("/xml/openid").getText();
				String transaction_id=doc.selectSingleNode("/xml/transaction_id").getText();
				//判断是充值还是支付
				transaction2zcService.editZcOrderStatus(openId, outTradeNo, transaction_id, new BigDecimal(total_fee));
				String returnStr="<xml>"
									+ "<return_code><![CDATA[SUCCESS]]>"
									+ "</return_code><return_msg><![CDATA[]]></return_msg>"
								+ "</xml>";
				httpResponse.getWriter().write(returnStr);   //告诉微信服务器，我收到信息了，不要在调用回调action了
			
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
//=====================================邮宝账户支付===========================================	
/*	*//**
	 * 0019接口
	 * 邮宝账户支付的方法调用
	 * @param out_trade_no
	 * @param total_fee
	 * @param body
	 * @param openid
	 * @param httpRequest
	 * @return
	 *//*
	@RequestMapping("ybPayApi")
	@ResponseBody
	public  HashMap<String, Object> ybPayApi(
			@RequestParam("out_trade_no") String out_trade_no,
			@RequestParam("total_fee") int total_fee,
			@RequestParam("openid") String openid,
			@RequestParam("curPage") String curPage) {
		HashMap<String, Object> response = new HashMap<>();
		try {
			if(transaction2zcService.ybPayTransaction(openid, out_trade_no, new BigDecimal(total_fee))){
				response.put("responseCode", "00000");
				response.put("response", ConstantConfig.PAY_SUCCESS);
				response.put("responseURL", SysConfig.notify_url_yb+curPage);
			}else{
				response.put("responseCode", "E0001");
				response.put("response", ConstantConfig.PAY_FAILED);
			}
			
		} catch (Exception e) {
			response.put("responseCode", "E0001");
			response.put("response", ConstantConfig.PAY_FAILED);
		}
		return response;
	}*/
	
	/**
	 * 0020接口
	 * 收入接口
	 * @param userId
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("incomeList")
	public  String incomeList(
			@RequestParam("userId") Integer userId,HttpServletRequest httpRequest) {
		try {
			List<LogIncome> incomeList=transaction2zcService.queryIncomeList(userId);
			httpRequest.setAttribute("responseCode", "00000");
			httpRequest.setAttribute("response", ConstantConfig.QUERY_SUCCESS);
			httpRequest.setAttribute("incomeList", incomeList);
			
		} catch (Exception e) {
			e.printStackTrace();
			httpRequest.setAttribute("responseCode", "E0001");
			httpRequest.setAttribute("response", ConstantConfig.QUERY_FAILED);
		}
		return "forward:/web/person/income.jsp";
	}
	
	/**
	 * 0021接口
	 * 支出接口
	 * @param userId
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("userBillList")
	public  String userBillList(
			@RequestParam("userId") Integer userId,HttpServletRequest httpRequest) {
		try {
			List<LogNoruserbill> userBillList=transaction2zcService.queryUserBillList(userId);
			httpRequest.setAttribute("responseCode", "00000");
			httpRequest.setAttribute("response", ConstantConfig.QUERY_SUCCESS);
			httpRequest.setAttribute("userBillList", userBillList);
			
		} catch (Exception e) {
			httpRequest.setAttribute("responseCode", "E0001");
			httpRequest.setAttribute("response", ConstantConfig.QUERY_FAILED);
		}
		return "forward:/web/person/pay.jsp";
	}
	
}